/*
 * Client.java
 *
 * Created on Mar 5, 2011, 11:25:24 AM
 */
package bitetorrent.form;

import bitetorrent.Torrent;
import bitetorrent.helper.Request;
import bitetorrent.trackerComm.TrackerHandler;
import bitetorrent.peersComm.PeerListener;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author user
 */
public class Client extends javax.swing.JFrame {

    public int selected = -999;

    ArrayList<Torrent> arrayTorrent = new ArrayList<Torrent>();
    ArrayList<TrackerHandler> handlers = new ArrayList<TrackerHandler>();
    PeerListener clientListener = new PeerListener(WIDTH);
    Setting setting;

    /** Creates new form Client */
    public Client() {
        initComponents();

        // Bersih - bersih
        arrayTorrent.clear();
        logAksi.removeAll();
        logFile.removeAll();

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width - w) / 2;
        int y = (dim.height - h) / 2;

        // Move the window
        this.setLocation(x, y);

        // Run Listener
        clientListener.start();

        // Create Setting
        setting = new Setting();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel9 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        logFile = new java.awt.List();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        logAksi = new java.awt.List();
        AddTorrent = new javax.swing.JButton();
        Download = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        URL = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        port = new javax.swing.JTextField();
        CreateTorrent = new javax.swing.JButton();
        partisi = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        FileAsal = new javax.swing.JTextField();
        fileTujuan = new javax.swing.JTextField();
        GetName = new javax.swing.JButton();
        Rename = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemSetting = new javax.swing.JMenuItem();

        jLabel9.setText("jLabel9");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("bitetorrent (torrent that bite)");

        logFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logFileActionPerformed(evt);
            }
        });

        jLabel2.setText("Nama File :");

        jLabel1.setText("Log :");

        AddTorrent.setText("Add Torrent");
        AddTorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddTorrentActionPerformed(evt);
            }
        });

        Download.setText("Download");
        Download.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DownloadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(logFile, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 468, Short.MAX_VALUE)
                        .addComponent(AddTorrent)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Download, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(24, 24, 24))
                    .addComponent(jLabel1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(logAksi, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)))
                .addGap(0, 0, 0))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(Download, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(AddTorrent))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logFile, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logAksi, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel3.setText("URL");

        jLabel4.setText("Port");

        CreateTorrent.setText("Create Torrent");
        CreateTorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CreateTorrentActionPerformed(evt);
            }
        });

        partisi.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "32", "64", "128", "256", "512", "1024", "2048", "4096" }));

        jLabel5.setText("Ukuran Partisi");

        jLabel6.setText("KB");

        GetName.setText("GetName");
        GetName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GetNameActionPerformed(evt);
            }
        });

        Rename.setText("Rename");
        Rename.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RenameActionPerformed(evt);
            }
        });

        jLabel7.setText("Nama File Torrent");

        jLabel8.setText("Nama File Asal");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(URL, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(partisi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(fileTujuan, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Rename)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                        .addComponent(CreateTorrent))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(FileAsal, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(GetName))
                    .addComponent(jLabel8))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(URL, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(partisi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(24, 24, 24)
                .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FileAsal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(GetName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(CreateTorrent)
                    .addComponent(fileTujuan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Rename))
                .addContainerGap())
        );

        jMenuFile.setText("File");

        jMenuItemSetting.setText("Setting");
        jMenuItemSetting.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenuItemSettingMouseClicked(evt);
            }
        });
        jMenuFile.add(jMenuItemSetting);

        jMenuBar1.add(jMenuFile);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void AddTorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddTorrentActionPerformed

        try {
            /*
             * KAMUS LOKAL
             */
            String namaFile = null;
            /*
             * ALGORITMA
             */
            // Open JFileChooser
            JFileChooser Open = new JFileChooser();
            // Set Filter
            Open.setFileFilter(new FileFilter() {

                public boolean accept(File f) {
                    return f.getName().toLowerCase().endsWith(".torrent") || f.isDirectory();
                }

                public String getDescription() {
                    return "torrent files";
                }
            });
            // Set Current Directory
            Open.setCurrentDirectory(new File(""));
            int retval = Open.showOpenDialog(this);
            if (retval == JFileChooser.APPROVE_OPTION) {
                File F = Open.getSelectedFile();
                namaFile = F.getAbsolutePath();
            } // Read and Parse File
            // Disimpan dalam Object Torrent
            Torrent torrent = new Torrent();
            torrent.ReadTorrent(namaFile);
            // Masukkan ke arrayTorrent
            arrayTorrent.add(torrent);
            selected = arrayTorrent.size() - 1; // update selected
            // Tulis ke log
            logAksi.add("Add Torrent File - " + namaFile);
            logFile.add("File: " + torrent.fileName + ", Length:" + torrent.fileLength + ", Announce: " + torrent.announce);
            //logFile.add(ArrayNamaFile.get(selected));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_AddTorrentActionPerformed

    private void CreateTorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CreateTorrentActionPerformed
        Torrent temp = new Torrent();
        // Membuat torrent jika berhasil
        if ((FileAsal.getText() == null ? "" != null : !FileAsal.getText().equals(""))
                || (fileTujuan.getText() == null ? "" != null : !fileTujuan.getText().equals(""))
                || (URL.getText() == null ? "" != null : !URL.getText().equals(""))) // sudah terisi semua
        {
            try {
                temp.CreateTorrent(FileAsal.getText(), fileTujuan.getText(), Integer.parseInt(partisi.getSelectedItem().toString()) * 1000, URL.getText() + ":" + port.getText() + "/");
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            arrayTorrent.add(temp);
            selected = arrayTorrent.size() - 1; //update selected

            // Register File
            String parameterRequest = "register=" + temp.fileName;
            String response = Request.sendGetRequest(temp.announce, parameterRequest);

            // Log
            logAksi.add("Add Torrent File - " + fileTujuan.getText());
            logAksi.add("File: " + temp.fileName + ", Length:" + temp.fileLength + ", Announce: " + temp.announce);
            logAksi.add("Register file : " + parameterRequest);
            logAksi.add("Response : " + response);
            logFile.add("File: " + temp.fileName + ", Length:" + temp.fileLength + ", Announce: " + temp.announce);
        } else {
            Warning b = new Warning(this, true);
            b.setVisible(true);
        }
    }//GEN-LAST:event_CreateTorrentActionPerformed

    private void DownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DownloadActionPerformed

        if (selected >= 0) {
            // Ambil object torrent
            Torrent torrent = arrayTorrent.get(selected);

            // Buat thread untuk melakukan request ke tracker
            TrackerHandler handler = new TrackerHandler(torrent);
            handlers.add(handler);
            handler.start();

            // Tulis ke log
            logAksi.add("Now is Downloading " + torrent.fileName);
        } else {
            // Terdapat kesalahan
            Warning warning = new Warning(this, true);
            warning.Peringatan.setText("Tidak ada file terpilih");
            warning.show();
        }
    }//GEN-LAST:event_DownloadActionPerformed

    private void logFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logFileActionPerformed
        // TODO add your handling code here:
        selected = logFile.getSelectedIndex();
    }//GEN-LAST:event_logFileActionPerformed

    private void GetNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GetNameActionPerformed
        JFileChooser Open = new JFileChooser();
        Open.setCurrentDirectory(new File(""));
        int x = Open.showOpenDialog(this);
        if (x == JFileChooser.APPROVE_OPTION) {
            File F = Open.getSelectedFile();
            FileAsal.setText(F.getAbsolutePath());
        }
    }//GEN-LAST:event_GetNameActionPerformed

    private void RenameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenameActionPerformed
        JFileChooser Save = new JFileChooser();
        Save.setFileFilter(new FileFilter() {

            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".torrent")
                        || f.isDirectory();
            }

            public String getDescription() {
                return "torrent files";
            }
        });
        Save.setCurrentDirectory(new File(""));
        int retval = Save.showSaveDialog(this);
        if (retval == JFileChooser.APPROVE_OPTION) {
            File F = Save.getSelectedFile();
            fileTujuan.setText(F.getAbsolutePath());
        }
    }//GEN-LAST:event_RenameActionPerformed

    private void jMenuItemSettingMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItemSettingMouseClicked
        setting.setVisible(true);
    }//GEN-LAST:event_jMenuItemSettingMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Client().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddTorrent;
    private javax.swing.JButton CreateTorrent;
    private javax.swing.JButton Download;
    private javax.swing.JTextField FileAsal;
    private javax.swing.JButton GetName;
    private javax.swing.JButton Rename;
    private javax.swing.JTextField URL;
    private javax.swing.JTextField fileTujuan;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuItemSetting;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private java.awt.List logAksi;
    private java.awt.List logFile;
    private javax.swing.JComboBox partisi;
    private javax.swing.JTextField port;
    // End of variables declaration//GEN-END:variables
}
